package local

import (
	"encoding/json"
	"fmt"
	"strconv"
)

/*
	主要函数:
		GetMapValue (interface{} 为 map 时取里面的值)。
		StrValue (任何值转字符串)
*/

// AtoI 字符串转数字 (str)
func AtoI(str string) int {
	num, err := strconv.Atoi(str)
	if err != nil {
		return 0
	}
	return num
}

// Itoa 数字转字符串 (num)
func Itoa(num int) string {
	str := strconv.Itoa(num)
	return str
}

// TypeOf 获取数据类型
func TypeOf(v interface{}) string {
	return fmt.Sprintf("%T", v)
}

// GetMapValue (map[string]interface{}, key) 获取 map 中 key 的值, interface{} 转化为 map 并取值。没有返回 ""
func GetMapValue(m interface{}, key string) string {
	if b, err := json.Marshal(m); err == nil {
		m1 := make(map[string]interface{})
		err = json.Unmarshal(b, &m1)
		if err == nil {
			return StrValue(m1[key])
		}
	}
	return ""
}

// InArray .
func InArray(target string, strArray []string) bool {
	for _, element := range strArray {
		if target == element {
			return true
		}
	}
	return false
}

// StrValue 任何值转 string
func StrValue(value interface{}) string {
	var key string = ""
	if value == nil {
		return key
	}
	switch value.(type) {
	case float64:
		ft := value.(float64)
		key = strconv.FormatFloat(ft, 'f', -1, 64)
	case float32:
		ft := value.(float32)
		key = strconv.FormatFloat(float64(ft), 'f', -1, 64)
	case int:
		it := value.(int)
		key = strconv.Itoa(it)
	case uint:
		it := value.(uint)
		key = strconv.Itoa(int(it))
	case int8:
		it := value.(int8)
		key = strconv.Itoa(int(it))
	case uint8:
		it := value.(uint8)
		key = strconv.Itoa(int(it))
	case int16:
		it := value.(int16)
		key = strconv.Itoa(int(it))
	case uint16:
		it := value.(uint16)
		key = strconv.Itoa(int(it))
	case int32:
		it := value.(int32)
		key = strconv.Itoa(int(it))
	case uint32:
		it := value.(uint32)
		key = strconv.Itoa(int(it))
	case int64:
		it := value.(int64)
		key = strconv.FormatInt(it, 10)
	case uint64:
		it := value.(uint64)
		key = strconv.FormatUint(it, 10)
	case string:
		key = value.(string)
	case []byte:
		key = string(value.([]byte))
	default:
		newValue, _ := json.Marshal(value)
		key = string(newValue)
	}
	return key
}
